package com.xiaobawang.hundouluo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.xiaobawang.hundouluo.service.UserService;
import com.xiaobawang.hundouluo.utils.SharedPreferencesUtil;
import com.xiaobawang.hundouluo.utils.TimingButton;

import org.json.JSONException;
import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.utils.SMSLog;

public class UserCheckActivity extends AppCompatActivity implements View.OnClickListener {

    private TimingButton timingButton;
    private EditText edt1, edt2;
    private String phoneNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usercheck);

        //完成userCheck的BroadCastUserCheck的注册
        receiverUserCheck = new UserCheckActivity.UserCheckReceiver();
        IntentFilter filterUserCheck = new IntentFilter();
        filterUserCheck.addAction("com.xiaobawang.hundouluo.receiver.userCheck");
        UserCheckActivity.this.registerReceiver(receiverUserCheck, filterUserCheck);

        findViewById(R.id.activity_usercheck_btn_check).setOnClickListener(this);
        findViewById(R.id.activity_usercheck_btn_cancel).setOnClickListener(this);
        findViewById(R.id.activity_usercheck_btn_verification).setOnClickListener(this);

        timingButton = findViewById(R.id.activity_usercheck_btn_verification);
        edt1 = findViewById(R.id.activity_usercheck_et_phoneNumber);
        edt2 = findViewById(R.id.activity_usercheck_et_verifyNumber);

        EventHandler eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                mHandler.sendMessage(msg);
            }
        };

        SMSSDK.registerEventHandler(eh);//注册短信回调

    }

    BroadcastReceiver receiverUserCheck;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //将广播接收器注销
        UserCheckActivity.this.unregisterReceiver(receiverUserCheck);
    }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            Log.e("event", "event=" + event);
            if (result == SMSSDK.RESULT_COMPLETE) {
                System.out.println("---------result" + event);
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码成功
                    String userName = ((EditText) findViewById(R.id.activity_usercheck_et_userName)).getText().toString().trim();
                    String phone = ((EditText) findViewById(R.id.activity_usercheck_et_phoneNumber)).getText().toString().trim();
                    Intent sIntent = new Intent(UserCheckActivity.this, UserService.class);
                    sIntent.putExtra("type", "checkUser");
                    sIntent.putExtra("username", userName);
                    sIntent.putExtra("phone", phone);
                    startService(sIntent);
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //已经验证
                    Toast.makeText(getApplicationContext(), "验证码已发送", Toast.LENGTH_SHORT).show();
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    //已经验证
                    Toast.makeText(getApplicationContext(), "获取国家列表成功", Toast.LENGTH_SHORT).show();
                }
            } else {
                ((Throwable) data).printStackTrace();
                Toast.makeText(UserCheckActivity.this, "注册失败！验证码错误", Toast.LENGTH_SHORT).show();
                int status = 0;
                try {
                    ((Throwable) data).printStackTrace();
                    Throwable throwable = (Throwable) data;

                    JSONObject object = new JSONObject(throwable.getMessage());
                    String des = object.optString("detail");
                    status = object.optInt("status");
                    if (!TextUtils.isEmpty(des)) {
                        Toast.makeText(UserCheckActivity.this, des, Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (JSONException e) {
                    SMSLog.getInstance().w(e);
                }
            }
        }
    };

    protected void onDestory() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.activity_usercheck_btn_verification:
                timingButton.start();
                SMSSDK.getVerificationCode("86", edt1.getText().toString());
                phoneNumber = edt1.getText().toString();
                break;

            case R.id.activity_usercheck_btn_check:
                String userName = ((EditText) findViewById(R.id.activity_usercheck_et_userName)).getText().toString().trim();
                String phone = ((EditText) findViewById(R.id.activity_usercheck_et_phoneNumber)).getText().toString().trim();

                if (userName.length() == 0 || phone.length() == 0) {
                    Toast.makeText(UserCheckActivity.this, "请将信息填写完整!", Toast.LENGTH_LONG).show();
                    return;
                } else {
                    SMSSDK.submitVerificationCode("86", phoneNumber, edt2.getText().toString());
                }
                break;

            case R.id.activity_usercheck_btn_cancel :
                finish();
                break;

        }

    }

    class UserCheckReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("userCheckResult");
            String userName = ((EditText) findViewById(R.id.activity_usercheck_et_userName)).getText().toString().trim();
            Log.e("RegisterActivity", result);

            if (result.equalsIgnoreCase("success")) {
                Toast.makeText(UserCheckActivity.this, "验证成功!", Toast.LENGTH_LONG).show();
                SharedPreferencesUtil.write(UserCheckActivity.this, "userCheck", "uname", userName);
                startActivity(new Intent(UserCheckActivity.this, PasswordChange.class));
            } else {
                Toast.makeText(UserCheckActivity.this, "验证失败!用户名与手机号不匹配!", Toast.LENGTH_LONG).show();
            }
        }
    }
}
